import { useEffect, useState } from 'react'

//防抖
export const useDebounce = <V,>(value: V, delay: number = 500) => {
  const [debounceValue, setDebounceValue] = useState(value)

  useEffect(() => {
    const time = setTimeout(() => {
      setDebounceValue(value)
    }, delay)

    return () => clearTimeout(time)
  }, [value, delay])

  return debounceValue
}

//节流
// export const throttle = (callback, delay = 500, immediate = false) => {
//   // 定时器方式
//   let time = null
//   //时间戳方式
//   let pre

//   return function (...arg) {
//     if (immediate) {
//       //时间戳方式
//       if (!pre || Date.now() - pre >= delay) {
//         callback.apply(null, arg)
//         pre = Date.now()
//       }
//     } else {
//       // 定时器方式
//       if (time) return
//       time = setTimeout(() => {
//         callback.apply(null, arg)
//         time = null
//       }, delay)
//     }
//   }
// }

// 自定义hook：只执行一次
export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback()
  }, [])
}

// 清除对象中值为空的属性
export const cleanObj = (obj: object) => {
  let target = { ...obj }
  Object.keys(target).forEach(key => {
    // @ts-ignore
    const value = target[key]
    if (value === '') {
      // @ts-ignore
      delete target[key]
    }
  })

  return target
}
